package com.liu.nb.controller;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liu.nb.entity.SysMenu;
import com.liu.nb.entity.SysRoleMenu;
import com.liu.nb.entity.SysUser;
import com.liu.nb.util.Result;
import com.liu.nb.util.dto.SysMenuDto;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuziyi
 * @since 2021-08-05
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends BaseController{
    /*
    * 获取当前用户的菜单和权限信息
    * */
    @RequestMapping("/nav")
    public Result nav(Principal principal) {
        SysUser sysUser = sysUserService.getByUsername(principal.getName());
        //获取权限信息
        String authorityInfo = sysUserService.getUserAuthorityInfo(sysUser.getId());
        //把权限字符串转换成数组
        String[] strings = StringUtils.tokenizeToStringArray(authorityInfo, ",");
        //获取导航栏信息，这里没有传递用户参数，是因为再方法体中通过security的上下文来获取了。
        List<SysMenuDto> userNav = sysMenuService.getUserNav();
        return Result.success(MapUtil.builder()
                .put("authorities", strings)
                .put("nav", userNav)
                .map()
        );
    }
    @PreAuthorize("hasRole('admin')")
    @RequestMapping("/info/{id}")
    public Result getInfo(@PathVariable("id") Long id){
        return  Result.success(sysMenuService.getById(id));
    }

    @RequestMapping("/list")
    public Result list(){
        List<SysMenu> menuTree = sysMenuService.getMenuTree();
        return  Result.success(menuTree);
    }
    @PreAuthorize("hasRole('admin')")
    @PostMapping("/save")
    public Result add(@Validated @RequestBody SysMenu sysMenu){
        sysMenu.setCreated(LocalDateTime.now());
        boolean save = sysMenuService.save(sysMenu);
        return  Result.success(save);
    }
    @PreAuthorize("hasRole('admin')")
    @PostMapping("/update")
    public Result update(@Validated @RequestBody SysMenu sysMenu){
        sysMenu.setUpdated(LocalDateTime.now());

        boolean b = sysMenuService.updateById(sysMenu);
        //清除该菜单的缓存
        sysUserService.clearAuthorityInfoByMenuId(sysMenu.getId());
        return  Result.success(b);
    }
    @PreAuthorize("hasRole('admin')")
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Long id){
        int count = sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", id));
        if (count>0){
            return Result.fail("请先删除子菜单");
        }
//        清除缓存
        sysUserService.clearAuthorityInfoByMenuId(id);
        boolean b = sysMenuService.removeById(id);
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("menu_id",id));
        return Result.success(b);
    }
}
